package com.wwg.springboard;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Outline;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewOutlineProvider;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

public class RadiusImageView extends AppCompatImageView {
    private float mRadius = 0f;
    private ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            int measuredWidth = view.getMeasuredWidth();
            int measuredHeight = view.getMeasuredHeight();

            outline.setRoundRect(
                    0,
                    0,
                    measuredWidth,
                    measuredHeight,
                    mRadius);
        }
    };

    public RadiusImageView(Context context) {
        this(context, null);
    }

    public RadiusImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RadiusImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RadiusImageView);
        mRadius = typedArray.getDimension(R.styleable.RadiusImageView_android_radius, 0f);
        typedArray.recycle();
        setClipToOutline(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        setOutlineProvider(viewOutlineProvider);
        invalidateOutline();
    }
}
